//
//  AdView.m
//  mytown007
//
//  Created by Vescky on 13-12-20.
//  Copyright (c) 2013年 vescky. All rights reserved.
//

#import "AdView.h"
#import "AdViewData.h"
#import "UIImageView+MJWebCache.h"
#import "WebAppsConstant.h"
#import "AppDelegate.h"
#import "NewsDetailViewController.h"

@implementation MyUIScrollView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!self.dragging)
    {
        [[self nextResponder] touchesBegan:touches withEvent:event];
    }
    [super touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!self.dragging)
    {
        [[self nextResponder] touchesMoved:touches withEvent:event];
    }
    [super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!self.dragging)
    {
        [[self nextResponder] touchesEnded:touches withEvent:event];
    }
    [super touchesEnded:touches withEvent:event];
}
@end

@implementation AdView

#define ADIMG_INDEX 888
#define ADTITLE_INDEX   889
#define AD_BOTTOM_HEIGHT    0//12.f

@synthesize sourceArr,bgImage,currentIndex;
@synthesize labelFont,labelBgColor,labelBgImage,labelOccupyPercentage,labelAlpha,labelTextColor,actionLink;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
    }
    return self;
}

- (void)loadAds {
    [self initData];
    [self initView];
    [self resetTimer];
    [self AddAdImg:sourceArr];
}

- (void)resetTimer {
    [self stopTimer];
    adTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(changedAdTimer:) userInfo:nil repeats:YES];
}

- (void)stopTimer {
    if (adTimer) {
        [adTimer invalidate];
    }
}

- (void)initData {
    if (!labelAlpha) {
        labelAlpha = .6;
    }
    if (!labelBgColor) {
        labelBgColor = [UIColor clearColor];
    }
    if (!labelTextColor) {
        labelTextColor = [UIColor whiteColor];
    }
    if (!labelOccupyPercentage) {
        labelOccupyPercentage = 10;
    }
    if (!labelFont) {
        labelFont =[UIFont fontWithName:@"Helvetica-Bold" size:14.f];
    }
}

- (void)initView {
    /* ad scroll view */
    adScrollView = [[MyUIScrollView alloc] initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height-AD_BOTTOM_HEIGHT)];
    [adScrollView setDelegate:self];   // set delegate
    [adScrollView setScrollEnabled:YES];
    [adScrollView setPagingEnabled:YES];
    [adScrollView setShowsHorizontalScrollIndicator:NO];
    [adScrollView setShowsVerticalScrollIndicator:NO];
    [adScrollView setAlwaysBounceVertical:NO];
    [adScrollView setContentSize:CGSizeMake(320.f*([sourceArr count]>0?[sourceArr count]:0), adScrollView.frame.size.height)];
    [self addSubview:adScrollView];
    
    /* infomation */
    UIImageView *img_info = [[UIImageView alloc] initWithFrame:CGRectMake(0.f, self.frame.size.height-24.f-AD_BOTTOM_HEIGHT, adScrollView.frame.size.width, 24.f)];
    [img_info setBackgroundColor:[UIColor blackColor]];
    [img_info setAlpha:labelAlpha];
    [self addSubview:img_info];
    
    /* page ctrl */
    adPageController = [[UIPageControl alloc] initWithFrame:CGRectMake(0.f, 0.f, 74.f, 8.f)];
    [adPageController setCenter:CGPointMake(adScrollView.frame.size.width-74.f/2.f - 10, self.frame.size.height-AD_BOTTOM_HEIGHT-24.f/2.f)];
    [adPageController setUserInteractionEnabled:YES];
    [adPageController setAutoresizesSubviews:YES];
    [adPageController setAlpha:1.f];
    [adPageController setCurrentPageIndicatorTintColor:[UIColor whiteColor]];//GetColorWithRGB(97, 42, 100)
    [adPageController setCurrentPage:0];
    [adPageController setNumberOfPages:([sourceArr count]>0?[sourceArr count]:0)];
    [self addSubview:adPageController];
    
    /* label */
    labelAdWords = [[UILabel alloc] initWithFrame:CGRectMake(img_info.frame.origin.x+6.f, 0.f, 320.f-adPageController.frame.size.width-AD_BOTTOM_HEIGHT - 15, 24.f)];
    [labelAdWords setTag:ADTITLE_INDEX];
    [labelAdWords setBackgroundColor:labelBgColor];
    [labelAdWords setTextColor:labelTextColor];
//    [labelAdWords setAlpha:labelAlpha];
    [labelAdWords setFont:labelFont];
    if ([sourceArr count] > 0) {
        AdViewData *aData = (AdViewData*)[sourceArr objectAtIndex:0];
        [labelAdWords setText:aData.adWords];
    }
    
    [labelAdWords setTextAlignment:0];
    [labelAdWords setLineBreakMode:0|4];
    [labelAdWords setFont:[UIFont systemFontOfSize:12.0]];
    [img_info addSubview:labelAdWords];
    
    /* bottom line */
//    UIImageView *img_AdBottomLine = [[UIImageView alloc] initWithFrame:CGRectMake(0.f, self.frame.size.height-AD_BOTTOM_HEIGHT, self.frame.size.width, AD_BOTTOM_HEIGHT)];
//    [img_AdBottomLine setImage:[UIImage imageNamed:@"广告底线"]];
//    [self addSubview:img_AdBottomLine];
    
}

#pragma mark - ----- -> 初始化添加广告图片
- (void)AddAdImg:(NSArray*)arr_adimgs
{
    for (int i = 0; i < ([sourceArr count]>0?[sourceArr count]:0); ++i)
    {
        UIImageView *img_Ad = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width*i, 0.f, self.frame.size.width, self.frame.size.height-AD_BOTTOM_HEIGHT)];
        AdViewData *aData = (AdViewData*)[sourceArr objectAtIndex:i];
//        [img_Ad setImage:aData.sImage/*[UIImage imageNamed:[self DownloadImgs:[arr_AdImgs objectAtIndex:i]]]*/];    /* -> 网络图片使用DownloadImgs下载图片 */
        [img_Ad setImageURLStr:aData.webImageLink placeholder:Default_Image_Normal];
        [img_Ad setTag:ADIMG_INDEX+i];
        [img_Ad setUserInteractionEnabled:YES];
        [img_Ad setContentMode:UIViewContentModeScaleAspectFill];
        [img_Ad setBackgroundColor:[UIColor blackColor]];
        [img_Ad setClipsToBounds:YES];
        [adScrollView addSubview:img_Ad];
    }
}


#pragma mark - ----- -> 点击广告
- (void)OpenAd:(int)iTag {
    AdViewData *aData = (AdViewData*)[sourceArr objectAtIndex:adPageController.currentPage];
    NSString *wLink = Webapp_News_Detail_Link(aData.recordId);
    NewsDetailViewController *ndViewController = [[NewsDetailViewController alloc] init];
    ndViewController.webappLink = wLink;
    ndViewController.detailInfo = aData.dataInfo;
    ndViewController.coverImage = [(UIImageView*)[adScrollView viewWithTag:ADIMG_INDEX + iTag] image];
    ndViewController.recordId = [NSString stringWithFormat:@"%d",aData.recordId];
    [[APP_DELEGATE navigationController] pushViewController:ndViewController animated:YES];
    NSLog(@"link: %@", wLink);
}

#pragma mark - ----- -> 切换广告
static int cur_count = -1;
- (void)changedAdTimer:(NSTimer *)timer
{
    cur_count = adPageController.currentPage;
    ++cur_count;
    adPageController.currentPage = (cur_count%[sourceArr count]);
    
    [UIView animateWithDuration:.7f animations:^{
        AdViewData *aData = (AdViewData*)[sourceArr objectAtIndex:adPageController.currentPage];
        [labelAdWords setText:aData.adWords];
        adScrollView.contentOffset = CGPointMake(adPageController.currentPage*320.f, 0.f);
    }];
}

#pragma mark - ----- -> scrollView opt
enum _jmpFalg { NORMAL = 0, LAST = -1, FIRST = 1 };
BOOL bJmp = NORMAL;
static float maxLoc = 0.f, minLoc = 0.f;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    maxLoc = (maxLoc>scrollView.contentOffset.x)?maxLoc:scrollView.contentOffset.x;
    minLoc = (minLoc<scrollView.contentOffset.x)?minLoc:scrollView.contentOffset.x;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self resetTimer];
    do
    {
        if (maxLoc > ([sourceArr count]-1)*320.f)
        {
            bJmp = FIRST;
            break;
        }
        else if (minLoc < 0*320.f)
        {
            bJmp = LAST;
            break;
        }
        else
        {
            bJmp = NORMAL;
            break;
        }
    } while (TRUE);
    
    switch (bJmp)
    {
        case FIRST:
        {
            adPageController.currentPage = 0;
        }
            break;
        case LAST:
        {
            adPageController.currentPage = ([sourceArr count]>0?[sourceArr count]:0);
        }
            break;
        case NORMAL:
        {
            [adPageController setCurrentPage:scrollView.contentOffset.x/320.f];
        }
            break;
        default:
            break;
    }
    [UIView animateWithDuration:.7f animations:^{
        AdViewData *aData = (AdViewData*)[sourceArr objectAtIndex:adPageController.currentPage];
        [labelAdWords setText:aData.adWords];
        adScrollView.contentOffset = CGPointMake((adPageController.currentPage%[sourceArr count])*320.f, 0.f);
    }];
    maxLoc = minLoc = adScrollView.contentOffset.x;
}


#pragma mark ----- -> touches opt
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //UITouch *touch = [touches anyObject];
    //CGPoint startPos = [touch locationInView:self];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //UITouch *touch = [touches anyObject];
    //CGPoint movePos = [touch locationInView:self];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint endPos;
    UIImageView *lbl_AdImg;
    for (int i = 0; i < ([sourceArr count]>0?[sourceArr count]:0); ++i)
    {
        lbl_AdImg = (UIImageView *)[self viewWithTag:ADIMG_INDEX+i];
        endPos = [touch locationInView:lbl_AdImg];
        if (endPos.x >= 0.f && endPos.x <= 320.f)
            [self OpenAd:i];
    }
}

@end
